package com.activities;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.Adapters.CommentAdapter;
import com.Animations.AnimUtil;
import com.Data.Comment;
import com.Data.Comment.onAddCommentsCompleted;
import com.Data.Comment.onGetCommentsCompleted;
import com.Data.Post;
import com.Data.User;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureManagerClass.CreateBlurAsync;
import com.Managers.ThemeManager;
import com.PopUps.PopUpClass;
import com.SoapClasses.SoapUtil;
import com.TextFormat.UtilFonts;
import com.shareup.R;


public class ActivityComments extends Activity {

    private static String pathImage;

    private static boolean reverse;

    static RelativeLayout container;

    // DELAYERS
    public static void delayBackground(final int time) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                if (pathImage != null) {
                    CreateBlurAsync cbs = new CreateBlurAsync(Post.BLURCOMMENTS, container, pathImage);
                    cbs.setReverse(reverse);
                    cbs.execute();
                    reverse = false;
                }

            }

        }, time);
    }

    public static void delayGet(final Comment comment, final int last) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                comment.execute();
            }

        }, 1000);
    }

    public EditText textComment;

    private CommentAdapter adapter;

    private ListView commentList;

    private boolean empty;

    private int IDOwner;

    private int IDPicture;

    private TableRow listContainer;

    private ImageView refreshButton;

    private Button sendButton;

    private boolean shouldBackground;

    private TextView titleActivity;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            //
            return true;
        }
        //
        return super.onKeyUp(keyCode, event);
    }

    public void refreshComments(int last) {

        startRotateRefresh();

        Comment com = new Comment(this);
        com.setAction(Comment.ACTION_GET);
        com.setLast(last);
        com.setCallbackGet(new onGetCommentsCompleted() {

            @Override
            public void Completed(Comment[] result) {

                processResult(result);

            }
        });
        Post pic = new Post();
        pic.setID(IDPicture);
        com.setPicture(pic);

        delayGet(com, last);

    }

    public void setEmpty(boolean empty) {

        this.empty = empty;
    }

    public void updatePictureCounter(int count) {

        if (SoapUtil.MENU_VIEW != SoapUtil.MODE_FOLLOWERS
                    && SoapUtil.MENU_VIEW != SoapUtil.MODE_MINE)
            FragmentManagerClass.aExplore.updateComments(IDPicture, count);

        if (SoapUtil.MENU_VIEW == SoapUtil.MODE_MINE)
            FragmentManagerClass.aMine.updateComments(IDPicture, count);

    }

    private void addToList(Comment[] list) {

        if (adapter == null)
            adapter = new CommentAdapter(this, R.layout.item_comment, R.id.commentext);

        boolean wasUpdate = false;

        for (Comment com : list) {
            if (!adapter.contains(com))
                adapter.add(com, this.IDOwner);
            wasUpdate = true;
        }

        if (commentList.getAdapter() == null)
            commentList.setAdapter(adapter);

        if (wasUpdate)
            adapter.notifyDataSetChanged();

        stopRotateRefresh();

    }

    private void exit() {

        if (adapter != null)
            adapter.clearAnimations();
        finish();
        AnimUtil.getActivityTransition(this, false);
    }

    private void getViews() {

        // SETTING TITLE
        titleActivity = (TextView) findViewById(R.id.title_actionbar);
        // SETTING COMMENT TEXTBOX
        textComment = (EditText) findViewById(R.id.commentext);
        // SETTING SEND BUTTON
        sendButton = (Button) findViewById(R.id.btn_post_comment);
        sendButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Context context = v.getContext();
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                newComment(textComment.getText().toString());
                textComment.setText("");
            }
        });

        // SETTING LISTVIEW OF COMMENTS
        commentList = (ListView) findViewById(R.id.Listview);
        // SETTING THE CONTAINER LAYOUT OF THE ACTIVITY
        container = (RelativeLayout) findViewById(R.id.container_full);
        // SETTING LIST CONTAINER
        listContainer = (TableRow) findViewById(R.id.listContainer);
        // BUTTON BACK
        ImageView backB = (ImageView) findViewById(R.id.button_back);
        // LISTENER BUTTON BACK
        backB.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                exit();
            }
        });
        // BUTTON REFRESH
        refreshButton = (ImageView) findViewById(R.id.acomments_image_refresh);
        // LISTENER REFRESH
        refreshButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                startRotateRefresh();
                refreshComments(commentList.getCount());
            }
        });

        // LAYOUT TO FOCUS ON IT AND NOT THE TEXT
        LinearLayout fc = (LinearLayout) findViewById(R.id.container);
        fc.requestFocus();
        // SETTING TEXT FONT
        UtilFonts.setTextRegularFont(textComment, sendButton);
        UtilFonts.setTextBoldFont(titleActivity);
        // END OF THIS
        refreshComments(0);

    }

    private void newComment(String text) {

        if (text.trim().length() > 0) {
            Comment com = new Comment(this);
            com.setAction(Comment.ACTION_ADD);
            com.setCallbackAdd(new onAddCommentsCompleted() {

                @Override
                public void Completed(String result) {

                    refreshComments(commentList.getCount());

                }
            });

            String comm = "";
            try {
                comm = URLEncoder.encode(text, "UTF-8");
            }
            catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            User us = new User();
            us.setID(IDOwner);
            Post pic = new Post();
            pic.setID(IDPicture);
            pic.setUser(us);
            com.setPicture(pic);
            com.setMessage(comm);
            com.execute();
        }
        else
            textComment.setError(getResources().getString(R.string.error_empty_fields));

    }

    private void processResult(Comment[] result) {

        if (result.length > 0) {
            if (listContainer.getChildCount() > 0)
                AnimUtil.animatePopUp(listContainer, false, null);
            if (commentList.getCount() == 0)
                shouldBackground = true;

            addToList(result);

        }
        else {
            stopRotateRefresh();
        }
        if (adapter == null || adapter.getCount() == 0) {
            shouldBackground = true;
            empty = true;
            new PopUpClass(this).setMessage(getResources().getString(R.string.dialog_no_comments), R.drawable.comment_icon_normal, listContainer);
            stopRotateRefresh();

        }
        setBackground();

    }

    private void setBackground() {

        int count = commentList.getCount();

        if (empty) {
            shouldBackground = true;
            reverse = true;
            count = 1;

        }

        if (count > 0 && shouldBackground) {
            delayBackground(500);
            shouldBackground = false;
            empty = false;
        }

    }

    private void startRotateRefresh() {

        refreshButton.setClickable(false);
        RotateAnimation rotate = (RotateAnimation) AnimationUtils.loadAnimation(this, R.anim.effect_rotate_indef);
        refreshButton.startAnimation(rotate);
    }

    private void stopRotateRefresh() {

        refreshButton.clearAnimation();
        refreshButton.setClickable(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ThemeManager.setTheme(this);
        setContentView(R.layout.activity_comments);
        super.onCreate(savedInstanceState);

        FragmentManagerClass.aComment = this;

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            IDOwner = extras.getInt("IDOWNER");
            IDPicture = extras.getInt("IDPICTURE");
            pathImage = extras.getString("path");

            if (pathImage != null)
                shouldBackground = true;

        }

        getViews();
    }

}
